#!/bin/bash

function helpMessage(){
    echo "SYNOPSIS"
    echo "    ./deploy.sh -u <user> -p <passwd> -l <artifactory url>"
    echo "OPTIONS"
    echo "    -h: show help for prepare.sh"
    echo "    -u: specified artifactory user"
    echo "    -p: specified artifactory password"
    echo "    -l: specified artifactory url, like Nexus or JFrog repo-url"
}

CURDIR=$(cd $(dirname $0); pwd)
while getopts "hu:p:l:" opt; do
    case $opt in
    u)
        USER="$OPTARG"
        ;;
    p)
        PASSWD="$OPTARG"
        ;;
    l)
        ARTIFACTORY_URL="$OPTARG"
        ;;
    h)
        helpMessage
        exit 0
        ;;
    ?)
        echo "    There is unrecognized parameter!"
        helpMessage
        exit 1
        ;;
    esac
done

artifact_exist=`conan remote list | grep artifact | awk '{print $2}'`
if [ ! -n "$USER" ]; then
    echo "please specify the artifact user!"
    exit 1
fi
if [ ! -n "$PASSWD" ]; then
    echo "please specify the artifact password!"
    exit 1
fi
if [ ! -n "$ARTIFACTORY_URL" ] && [ "$artifact_exist" = "" ]; then
    echo "please specify the artifact address!"
    exit 1
elif [ "$artifact_exist" = "" ]; then
    conan remote add artifact $ARTIFACTORY_URL
elif [ ! -n "$ARTIFACTORY_URL" ]; then
    ARTIFACTORY_URL=$artifact_exist
elif [ "$ARTIFACTORY_URL" != "$artifact_exist" ]; then
    conan remote remove artifact
    conan remote add artifact $ARTIFACTORY_URL
fi

echo "##########################################################"
# echo "artifact user: $USER"
# echo "artifact passwd: $PASSWD"
echo "type: @CMAKE_BUILD_TYPE@"
echo "workspace: $CURDIR"
echo "artifact repo-url: $ARTIFACTORY_URL"
echo "##########################################################"

conan user -p $PASSWD -r artifact $USER
if [ $? -ne 0 ]; then
    echo "login nexus-artifactory-server failed, please check user/password or nexus server"
    exit 1
fi

conan export-pkg -pf @CMAKE_INSTALL_PREFIX@ @CMAKE_BINARY_DIR@/conanfile.py @COMPONENT_NAME@/@COMPONENT_VERSION@@components/stable -s build_type=@CMAKE_BUILD_TYPE@ --force > @CMAKE_BINARY_DIR@/deployinfo.txt
if [ $? -ne 0 ]; then
    echo "package @COMPONENT_NAME@/@COMPONENT_VERSION@@components/stable failed!"
    exit 1
fi
conan upload @COMPONENT_NAME@/@COMPONENT_VERSION@@components/stable -r artifact --all
if [ $? -ne 0 ]; then
    echo "upload @COMPONENT_NAME@/@COMPONENT_VERSION@@components/stable failed!"
    exit 1
fi

artifact_sha=`cat @CMAKE_BINARY_DIR@/deployinfo.txt | grep 'Packaging to' | awk '{print $3}'`
echo "artifactory_sha: $artifact_sha" >> @CMAKE_BINARY_DIR@/version.yaml
